<template>
  <div class="default-main ba-table-box">
    <el-alert
      class="ba-table-alert"
      v-if="baTable.table.remark"
      :title="baTable.table.remark"
      type="info"
      show-icon
    />
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="['refresh', 'comSearch', 'columnDisplay']"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <Table ref="tableRef" @action="baTable.onTableAction" />
    <!-- 表单 -->
    <!-- <PopupForm v-if="baTable.form.operate ? true : false" ref="formRef" /> -->
  </div>
</template>
<script lang="ts" setup>
import { ref, provide, onMounted, onBeforeUnmount, markRaw, inject } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { BusinessDevices } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useRoute, useRouter } from "vue-router";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useBackendMonitor } from "@/store/backend/EquipM/monitor"; //实时设备监控仓库
import { useAccess } from "@/store/backend/DeviceM/access";
import TagSearch from "@/components/tagSearch/index.vue";
import TagState from "@/components/dictTagState/index.vue";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { getDictData } from "@/utils/common";
import { useRegion } from "@/store/backend/SysM/region";

const formRef = ref();
const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const access = useAccess();
const router = useRouter();
const business = useBusiness();
const monitor = useBackendMonitor();
const dictionary = useDictionary();
const region = useRegion();
const navTabs = inject("navTabs") as any;

//全局事件总线
const { proxy } = useCurrentInstance();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + BusinessDevices)
      ? (navTabs as any).pageSizeMap.get(route.path + BusinessDevices)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(BusinessDevices), //该用户管理增删改查封装好的api
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("code"),
        label: "设备编号",
        prop: "code",
        align: "center",
        operatorPlaceholder: "精确搜索",
      },
      // {
      //   label: "设备名称",
      //   prop: "name",
      //   align: "center",
      //   operatorPlaceholder: "模糊搜索",
      //   operator: false,
      // },
      {
        show: filedShowOff("cname"),
        label: "所属企业",
        prop: "cname",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("addr"),
        label: "地址",
        prop: "addr",
        align: "center",
        width: "230",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("state"),
        label: "设备状态",
        prop: "state",
        align: "center",
        render: "customRender",
        customRender: markRaw(TagState),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("estate"),
        label: "运行状态",
        prop: "estate",
        align: "center",
        render: "tag",
        custom: { 1: "success", 0: "warning", 2: "danger" },
        replaceValue: {
          1: "正常",
          0: "异常",
          2: "告警",
        },
        operator: false,
      },
      // {
      //   label: "联系人",
      //   prop: "user",
      //   align: "center",
      //   operator: false,
      // },
      // {
      //   label: "联系方式",
      //   prop: "userPhone",
      //   align: "center",
      //   operator: false,
      // },
      {
        show: filedShowOff("process"),
        label: "废气处理工艺",
        prop: "process",
        align: "center",
        operator: false,
        render: "tag",
        replaceValue: {
          0: "喷淋",
          1: "两级活性炭",
        },
      },
      {
        show: filedShowOff("cTime"),
        label: "投用日期",
        prop: "cTime",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("replaceTime"),
        label: "活性炭更换日期",
        prop: "replaceTime",
        align: "center",
        operator: false,
      },
      {
        show: operatorShowOff(["/admin/system/evenhandle/list"]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "eventInfo",
            title: "维修记录",
            text: "维修记录",
            type: "primary",
            icon: "fa fa-wrench",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
        operator: false,
      },
    ],
    filter: { institution: route.query.institution, pageSize: pageSizeKeep() },
    acceptQuery: false, //不接受url的query参数并自动触发通用搜索
  }
);

//企业下维修详情
const handleRepair = (name: string, row: any) => {
  console.log("公司", row);
  business.devicesItem = row;
  router.push({ path: "/admin/EquipM/eventHandle", query: { eid: row.id } });
};
//双击跳转实况
proxy.eventBus.on("toMonitor", (row: any) => {
  console.log("双击", row);
  //从后台获取该设备数据跳转详情页
  // monitor
  //   .getnowList({ eid: row.gatewaycode })
  //   .then((res) => {
  //     access.getDevicesItem(row.id).then((res: any) => {
  //       //处理coordinate坐标系
  //       res.data.coordinate = JSON.parse(res.data.coordinate);
  //       monitor.deviceData = res.data;
  //       //为基本信息处理所属企业Map数据格式问题
  //       const business = useBusiness();
  //       const { companyList } = business;
  //       if (companyList.length === 0) {
  //         //为空就重新获取企业列表数据
  //         business.getCompanyList();
  //       }
  //     });
  //   })
  //   .catch((err) => {
  //     console.log(err);
  //   });
  monitor
    .getnowList({ eid: row.gatewaycode })
    .then((res) => {
      access.getDeviceByGateway(row.code, region.regionIds).then((res: any) => {
        //处理coordinate坐标系
        res.rows[0].coordinate = JSON.parse(res.rows[0].coordinate);
        monitor.deviceData = res.rows[0];
        //为基本信息处理所属企业Map数据格式问题
        const business = useBusiness();
        const { companyList } = business;
        if (companyList.length === 0) {
          //为空就重新获取企业列表数据
          business.getCompanyList();
        }
      });
    })
    .catch((err) => {
      console.log(err);
    });
  router.push({
    path: "/admin/EquipM/Monitordetail",
    query: { eid: row.gatewaycode }, //实况详情内事件需要eid
  });
});
//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("device_online_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();
onMounted(() => {
  console.log("当前路由", route.path);

  //全局事件总线
  const { proxy } = useCurrentInstance();
  proxy.eventBus.emit("pointer"); //el-table显示双击小手套
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(BusinessDevices);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      console.log("data", data);
      if (data.name == "eventInfo") {
        handleRepair(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
  console.log("router", router.currentRoute.value.path);
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);

onBeforeUnmount(() => {
  proxy.eventBus.off("toMonitor");
});
</script>
<style lang="scss" scoped></style>
